import { Component, Show, For, createMemo } from 'solid-js';
import { css } from 'solid-styled-components';
import { Item } from '../types/types';

interface Props {
  item: Item;
  class?: string;
}

interface CustomField {
  key: string;
  displayName: string;
  value: string;
  type: 'text' | 'url' | 'email' | 'date' | 'number' | 'boolean';
}

const CustomFieldsWrapper = css`
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1.5rem;
`;

const FieldsetTitle = css`
  font-size: 0.8rem;
  line-height: 0.8rem;
  color: var(--color4);
  top: -0.35rem;
  left: 1rem;
  background: white;
  padding: 0 0.5rem;
`;

const FieldsGrid = css`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-top: 0.5rem;
`;

const FieldItem = css`
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
`;

const FieldLabel = css`
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--bs-gray-600);
  text-transform: uppercase;
  letter-spacing: 0.5px;
`;

const FieldValue = css`
  font-size: 0.9rem;
  color: var(--bs-gray-800);
  word-break: break-word;
`;

const FieldLink = css`
  color: var(--color1);
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
  }
`;

const FieldBadge = css`
  display: inline-block;
  padding: 0.25rem 0.5rem;
  background: var(--color1);
  color: white;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
`;

const BooleanIndicator = css`
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.85rem;
`;

const StatusDot = css`
  width: 8px;
  height: 8px;
  border-radius: 50%;
  
  &.true {
    background: #28a745;
  }
  
  &.false {
    background: #dc3545;
  }
`;

export const CustomFields: Component<Props> = (props) => {
  // 过滤并处理 custom_ 开头的字段
  const customFields = createMemo(() => {
    if (!props.item.annotations) return [];
    
    const fields: CustomField[] = [];
    
    Object.entries(props.item.annotations).forEach(([key, value]) => {
      if (key.startsWith('custom_')) {
        fields.push({
          key,
          displayName: formatFieldName(key),
          value,
          type: detectFieldType(key, value)
        });
      }
    });
    
    // 按字段名排序
    return fields.sort((a, b) => a.displayName.localeCompare(b.displayName));
  });

  const renderFieldValue = (field: CustomField) => {
    switch (field.type) {
      case 'url':
        return (
          <a href={field.value} target="_blank" rel="noopener noreferrer" class={FieldLink}>
            {field.value}
          </a>
        );
      
      case 'email':
        return (
          <a href={`mailto:${field.value}`} class={FieldLink}>
            {field.value}
          </a>
        );
      
      case 'boolean':
        const isTrue = field.value.toLowerCase() === 'true';
        return (
          <div class={BooleanIndicator}>
            <div class={`${StatusDot} ${isTrue ? 'true' : 'false'}`}></div>
            {isTrue ? '是' : '否'}
          </div>
        );
      
      case 'date':
        return <span class={FieldValue}>{formatDate(field.value)}</span>;
      
      case 'number':
        return <span class={FieldValue}>{formatNumber(field.value)}</span>;
      
      default:
        // 检查是否是特殊值（如优先级、状态等）
        if (isSpecialValue(field.key, field.value)) {
          return <span class={FieldBadge}>{field.value}</span>;
        }
        return <span class={FieldValue}>{field.value}</span>;
    }
  };

  return (
    <Show when={customFields().length > 0}>
      <div class={`position-relative ${CustomFieldsWrapper} ${props.class || ''}`}>
        <div class={`position-absolute fw-semibold ${FieldsetTitle}`}>
          自定义字段
        </div>
        
        <div class={FieldsGrid}>
          <For each={customFields()}>
            {(field) => (
              <div class={FieldItem}>
                <div class={FieldLabel}>{field.displayName}</div>
                {renderFieldValue(field)}
              </div>
            )}
          </For>
        </div>
      </div>
    </Show>
  );
};

// 辅助函数

/**
 * 格式化字段名称：custom_priority -> 优先级
 */
function formatFieldName(key: string): string {
  // 移除 custom_ 前缀
  const name = key.replace(/^custom_/, '');
  
  // 预定义的字段名称映射
  const fieldNameMap: Record<string, string> = {
    'priority': '优先级',
    'status': '状态',
    'team': '团队',
    'owner': '负责人',
    'category': '类别',
    'type': '类型',
    'version': '版本',
    'environment': '环境',
    'region': '地区',
    'department': '部门',
    'project_id': '项目ID',
    'created_at': '创建时间',
    'updated_at': '更新时间',
    'contact': '联系方式',
    'email': '邮箱',
    'phone': '电话',
    'website': '网站',
    'repository': '代码仓库',
    'documentation': '文档',
    'support_level': '支持级别',
    'maintenance_status': '维护状态',
    'license_type': '许可证类型',
    'compliance': '合规性',
    'security_level': '安全级别'
  };
  
  // 如果有预定义映射，使用映射值
  if (fieldNameMap[name]) {
    return fieldNameMap[name];
  }
  
  // 否则进行基本格式化：下划线转空格，首字母大写
  return name
    .split('_')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

/**
 * 检测字段类型
 */
function detectFieldType(_key: string, value: string): CustomField['type'] {
  // URL 检测
  if (value.match(/^https?:\/\//)) {
    return 'url';
  }
  
  // 邮箱检测
  if (value.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
    return 'email';
  }
  
  // 布尔值检测
  if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
    return 'boolean';
  }
  
  // 日期检测
  if (value.match(/^\d{4}-\d{2}-\d{2}$/) || value.match(/^\d{4}\/\d{2}\/\d{2}$/)) {
    return 'date';
  }
  
  // 数字检测
  if (!isNaN(Number(value)) && value.trim() !== '') {
    return 'number';
  }
  
  return 'text';
}

/**
 * 检查是否是特殊值（需要特殊样式显示）
 */
function isSpecialValue(key: string, _value: string): boolean {
  const specialKeys = ['priority', 'status', 'level', 'type', 'category'];
  const keyName = key.replace(/^custom_/, '');
  
  return specialKeys.some(specialKey => keyName.includes(specialKey));
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  } catch {
    return dateString;
  }
}

/**
 * 格式化数字
 */
function formatNumber(numberString: string): string {
  try {
    const num = Number(numberString);
    return num.toLocaleString('zh-CN');
  } catch {
    return numberString;
  }
}
